//
//  RadioplayViewController.m
//  SunXi
//
//  Created by dllo on 15/11/28.
//  Copyright © 2015年 大远. All rights reserved.
//

#import "RadioplayViewController.h"

@interface RadioplayViewController ()<radioViewButtondelegate>
@property(nonatomic, assign) CirculationMode CirCulation;
@property (nonatomic, strong)CoreDataManager *manager;

@end

@implementation RadioplayViewController{
    NSTimer *_time;
    UIButton *_Collerbutton;
    BOOL _bollcollect;
    NSArray *_collarray;
    RadioModel *_collectmodel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    SV.backgroundColor = [UIColor whiteColor];
//MARK:按钮区
    RadioViewButtonView *buttonView = [[RadioViewButtonView alloc]init];
    buttonView.delegate = self;
    [SV addSubview:buttonView];
    [buttonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(SV.mas_bottom).offset(-64);
        make.height.mas_equalTo(64);
        make.width.equalTo(SV);
    }];
    self.manager = [CoreDataManager defaults];
    _Collerbutton = [UIButton buttonWithType:UIButtonTypeSystem];
    _Collerbutton.frame = CGRectMake(WIDTH - 70, 10, 24, 24);
    [self.navigationController.navigationBar.viewForBaselineLayout addSubview:_Collerbutton];
    [_Collerbutton addTarget:self action:@selector(collect:) forControlEvents:UIControlEventTouchUpInside];

    
    
    [self playMusicInNet];
    [self initScrollView];
    [self makeRightbutton];
    if (!_time) {
        _time = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeOver) userInfo:nil repeats:YES];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playMusicInNet) name:@"更换音乐" object:nil];
    
}

//MARK:判断是否收藏
- (BOOL)lookcollect{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Collect"];
    
    //添加约束  谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@",@"title",@"%@"],_collectmodel.title];
    request.predicate = predicate;
    
    NSError *error;
    _collarray = [[self.manager managedObjectContext] executeFetchRequest:request error:&error];
    
    if (_collarray.count > 0) {
        return YES;
    }
    
    return NO;
}
- (void)collbutton{

    _bollcollect = [self lookcollect];
  
    if (_bollcollect) {
        [_Collerbutton setImage:[UIImage imageNamed:@"ysc"] forState:UIControlStateNormal];
        [_Collerbutton setTintColor:[UIColor redColor]];
    }else{
        [_Collerbutton setImage:[UIImage imageNamed:@"wsc"] forState:UIControlStateNormal];
        [_Collerbutton setTintColor:BUTTONCOLOR];
    }
}
- (void)collect:(UIBarButtonItem *)buttonItem{
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Collect" inManagedObjectContext:self.manager.managedObjectContext];
    
    if (_bollcollect) {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        [fetchRequest setEntity:entity];
        
        NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@",@"title",@"%@"],_collectmodel.title];
        [fetchRequest setPredicate:predicate];
        NSError *error = nil;
        NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        for (Collect *temp in fetchedObjects) {
            [self.manager.managedObjectContext deleteObject:temp];
        }
        [self.manager saveContext];
        [_Collerbutton setImage:[UIImage imageNamed:@"wsc"] forState:UIControlStateNormal];
        [_Collerbutton setTintColor:BUTTONCOLOR];
        _bollcollect = NO;
    }else{
        Collect *ect = [[Collect alloc]initWithEntity:entity insertIntoManagedObjectContext:self.manager.managedObjectContext];
        ect.type = @"music";
        ect.code = _collectmodel.musicUrl;
        ect.title = _collectmodel.title;
        ect.radio = _collectmodel.radioid;
        ect.user = _collectmodel.userinfo[@"userinfo"][@"uname"];
        ect.image = _collectmodel.coverimg;
        [self.manager saveContext];
        [_Collerbutton setImage:[UIImage imageNamed:@"ysc"] forState:UIControlStateNormal];
        [_Collerbutton setTintColor:[UIColor redColor]];
        _bollcollect = YES;
    }
    
    
}

- (void)makeRightbutton{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    self.CirCulation = [ud integerForKey:@"cir"];
    [ud setInteger:self.CirCulation forKey:@"cir"];

    NSString *imagestr;
    switch (self.CirCulation) {
        case OrderCycle: {
            imagestr = @"shunxu";
            break;
        }
        case AllCycle: {
            imagestr = @"quanbu";
            break;
        }
        case SingleCycle: {
            imagestr = @"danqu";
            break;
        }
        case randomCycle: {
            imagestr = @"suiji";
            break;
        }
        default: {
            break;
        }
    }
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:imagestr] style:UIBarButtonItemStylePlain target:self action:@selector(Cirmyplay:)];
    self.navigationItem.rightBarButtonItem.tintColor = BUTTONCOLOR;

}
//MRRK:全局scrollView
- (void)initScrollView{
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    [SV addSubview:scrollView];
    scrollView.contentSize = CGSizeMake(3 * WIDTH, 0);
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.edges.equalTo(SV).with.insets(UIEdgeInsetsMake(0, 0, 64, 0));
    }];
    scrollView.backgroundColor = [UIColor yellowColor];
    scrollView.pagingEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.contentOffset = CGPointMake(WIDTH, 0);
    scrollView.bounces = NO;
    
    RadiotableView *view = [[RadiotableView alloc]init];
    view.frame = CGRectMake(0, 0, WIDTH, HEIGHT - 64);
    [scrollView addSubview:view];
    
    RadioPlayHomeView *HomeView = [[RadioPlayHomeView alloc]initWithFrame:CGRectMake(WIDTH, 0, WIDTH, HEIGHT - 64)];
    [scrollView addSubview:HomeView];
    
    RadioLookView *Lookview = [[RadioLookView alloc]initWithFrame:CGRectMake(2 * WIDTH, 0, WIDTH, HEIGHT - 64)];
    [scrollView addSubview:Lookview];
 
}


- (void)playMusicInNet{
    _collectmodel = [[RadioSavemodel shareSingleton].playlistArr objectAtIndex:[RadioSavemodel shareSingleton].playNumber];
     [self collbutton];
    if (![[_collectmodel musicUrl] isEqualToString:[RadioSavemodel shareSingleton].url]) {
 
      [[NSNotificationCenter defaultCenter] postNotificationName:@"开始音乐" object:nil];
    
    RadioModel *model = [[RadioSavemodel shareSingleton].playlistArr objectAtIndex:[RadioSavemodel shareSingleton].playNumber];
    [ShowMytext showHUDTextWithTitle:@"歌曲加载中,不要着急哦" View:SV];
    NSString *url = model.musicUrl;
    [RadioSavemodel shareSingleton].url = url;
    [RadioSavemodel shareSingleton].statre = YES;
        /**
         *      [RadioSavemodel shareSingleton].playlistArr = _arr;
         [RadioSavemodel shareSingleton].playNumber = indexPath.row;
         */
    
    [[myplay sharePlayer] playMusicWithURL:url];
        self.navigationItem.title = model.title;
    
    }
    
}
//MARK:控制按钮
- (void)play:(UIButton *)button{
    if ([RadioSavemodel shareSingleton].statre) {
        [RadioSavemodel shareSingleton].statre = NO;
        [button setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
        [[myplay sharePlayer] pause];
    }else{
        [RadioSavemodel shareSingleton].statre = YES;
        [button setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
        [[myplay sharePlayer] play];
    }
}
- (void)next{
    switch (self.CirCulation) {
        case OrderCycle: {
            [RadioSavemodel shareSingleton].playNumber += 1;
            break;
        }
        case AllCycle: {
            [RadioSavemodel shareSingleton].playNumber += 1;
            if ([RadioSavemodel shareSingleton].playNumber  == [RadioSavemodel shareSingleton].playlistArr.count - 1) {
                [RadioSavemodel shareSingleton].playNumber = 0;
            }
            break;
        }
        case SingleCycle: {
              [RadioSavemodel shareSingleton].playNumber += 1;
            break;
        }
        case randomCycle: {
            NSInteger i = arc4random() % ([RadioSavemodel shareSingleton].playlistArr.count - 1);
        start:
            if (i == [RadioSavemodel shareSingleton].playNumber) {
                i = arc4random() % ([RadioSavemodel shareSingleton].playlistArr.count - 1);
                goto start;
            }
            [RadioSavemodel shareSingleton].playNumber = i;
            break;
        }
        default: {
            break;
        }
    }
    
    
    if ([RadioSavemodel shareSingleton].playNumber  == [RadioSavemodel shareSingleton].playlistArr.count) {
        [ShowMytext showHUDTextWithTitle:@"已经是最后一首了" View:SV];
    }else{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"更换音乐" object:nil];

    }
}
- (void)last{
    switch (self.CirCulation) {
        case OrderCycle: {
            [RadioSavemodel shareSingleton].playNumber -= 1;
            break;
        }
        case AllCycle: {
            //            [ShowMytext showHUDTextWithTitle:@"全部循环" View:self.view];
            if ([RadioSavemodel shareSingleton].playNumber  < 0) {
                [RadioSavemodel shareSingleton].playNumber = [RadioSavemodel shareSingleton].playlistArr.count - 1;
            }
            break;
        }
        case SingleCycle: {
            [RadioSavemodel shareSingleton].playNumber -= 1;
            break;
        }
        case randomCycle: {
            NSInteger i = arc4random() % ([RadioSavemodel shareSingleton].playlistArr.count);
        start:
            if (i == [RadioSavemodel shareSingleton].playNumber) {
                i = arc4random() % ([RadioSavemodel shareSingleton].playlistArr.count);
                goto start;
            }
            [RadioSavemodel shareSingleton].playNumber = i;
            break;
        }
        default: {
            break;
        }
    }

    if ([RadioSavemodel shareSingleton].playNumber  < 0) {
        [ShowMytext showHUDTextWithTitle:@"已经是第一首了" View:SV];
    }else{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"更换音乐" object:nil];
    }
}

//MARK:切换循环模式
- (void)Cirmyplay:(UIBarButtonItem *)buttonItem{
    self.CirCulation ++;
    if (self.CirCulation > 3) {
        self.CirCulation = OrderCycle;
    }
    NSString *imagestr;
    switch (self.CirCulation) {
        case OrderCycle: {
            imagestr = @"shunxu";
            [ShowMytext showHUDTextWithTitle:@"顺序播放" View:self.view];
            break;
        }
        case AllCycle: {
            imagestr = @"quanbu";
            [ShowMytext showHUDTextWithTitle:@"全部循环" View:self.view];
            
            break;
        }
        case SingleCycle: {
            imagestr = @"danqu";
            [ShowMytext showHUDTextWithTitle:@"单曲循环" View:self.view];
            
            break;
        }
        case randomCycle: {
            imagestr = @"suiji";
            [ShowMytext showHUDTextWithTitle:@"随机播放" View:self.view];
            
            break;
        }
        default: {
            break;
        }
    }
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setInteger:self.CirCulation forKey:@"cir"];
    [buttonItem setImage:[UIImage imageNamed:imagestr]];


}

- (void)timeOver{
   
    if ([RadioSavemodel shareSingleton].statre) {
        [[myplay sharePlayer] play];
    }
    
    
    
    
    
    static BOOL next = YES;
    if (CMTimeGetSeconds([myplay sharePlayer].currentItem.currentTime) + 2>= CMTimeGetSeconds([myplay sharePlayer].currentItem.duration) && next){
        next = NO;
        NSLog(@"播放完成");
        [self timeOverclick];
    }else if (CMTimeGetSeconds([myplay sharePlayer].currentItem.currentTime) < 5){
        next = YES;
    }
}

- (void)timeOverclick{
    switch (self.CirCulation) {
        case SingleCycle: {
            [[myplay sharePlayer] seekToTime:CMTimeMakeWithSeconds(0.000, 1000000)];
            break;
        }
        default: {
            [self next];
            break;
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_Collerbutton removeFromSuperview];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)presentLeftMenuViewController:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
